<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @cancel="handleClose"
    @close="handleClose"
    size="80%"
  >
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <t-space direction="vertical" style="width: 100%" size="large">
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司名称（中文）" name="companyName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.companyName"
              />
              <div v-else class="form__text">{{ pageData.formData.companyName }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司名称（英文）" name="companyEngName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.companyEngName"
              />
              <div v-else class="form__text">{{ pageData.formData.companyEngName }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司简称（中文）" name="companyShortName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.companyShortName"
              />
              <div v-else class="form__text">{{ pageData.formData.companyShortName }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司简称（英文）" name="companyEngShortName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.companyEngShortName"
              />
              <div v-else class="form__text">{{ pageData.formData.companyEngShortName }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司地址（中文）" name="address">
              <t-input
                :showLimitNumber="true"
                maxlength="120"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.address"
              />
              <div v-else class="form__text">{{ pageData.formData.address }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="公司地址（英文）" name="engAddress">
              <t-input
                :showLimitNumber="true"
                maxlength="120"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.engAddress"
              />
              <div v-else class="form__text">{{ pageData.formData.engAddress }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="开户银行名（中文）" name="bankName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.bankName"
              />
              <div v-else class="form__text">{{ pageData.formData.bankName }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="开户银行名（英文）" name="bankEngName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.bankEngName"
              />
              <div v-else class="form__text">{{ pageData.formData.bankEngName }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="12">
            <t-form-item :labelWidth="170" label="开户银行地址（英文）" name="bankEngAddress">
              <t-input
                :showLimitNumber="true"
                maxlength="120"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.bankEngAddress"
              />
              <div v-else class="form__text">{{ pageData.formData.bankEngAddress }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="SWIFT CODE(BIC NO.)" name="swiftCode">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.swiftCode"
              />
              <div v-else class="form__text">{{ pageData.formData.swiftCode }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="银联号" name="unionPayCode">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.unionPayCode"
              />
              <div v-else class="form__text">{{ pageData.formData.unionPayCode }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="收款人账号" name="bankAccount">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.bankAccount"
              />
              <div v-else class="form__text">{{ pageData.formData.bankAccount }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="170" label="收款人英文名" name="payeeEngName">
              <t-input
                :showLimitNumber="true"
                maxlength="50"
                v-if="!pageData.readOnly"
                v-model="pageData.formData.payeeEngName"
              />
              <div v-else class="form__text">{{ pageData.formData.payeeEngName }}</div>
            </t-form-item>
          </t-col>
        </t-row>
      </t-space>

      <!-- <t-form-item label="备注" name="remark">
        <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" />
        <div v-else class="form__text">{{ pageData.formData.remark }}</div>
      </t-form-item> -->
    </t-form>
  </t-drawer>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import { type FormInstanceFunctions } from "tdesign-vue-next";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { EDIT_FORM_SAVE_BUTTON } from "@/common/constants";

// import { useUserStore } from "@/stores/modules/user";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    required: true
  }
});

const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/funder/findOne"; // 查询接口
const CREATE_FORM_PATH = "/funder/create"; // 创建接口
const UPDATE_FORM_PATH = "/funder/update"; // 更新接口

const pageData = reactive<Record<string, any>>({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    companyName: "",
    companyShortName: "",
    address: "",
    companyEngName: "",
    companyEngShortName: "",
    engAddress: "",
    bankName: "",
    bankEngName: "",
    bankEngAddress: "",
    swiftCode: "",
    bankAccount: "",
    payeeEngName: "",
    unionPayCode: ""
  },
  formRules: {
    companyName: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    companyShortName: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    address: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    bankName: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    bankEngName: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    bankEngAddress: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    swfitCode: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    unionPayCode: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    bankAccount: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ],
    payeeEngName: [
      {
        required: true,
        message: "请输入内容",
        type: "error",
        trigger: "blur"
      }
    ]
  }
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;
  }
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();

  /* validateResult 在校验没通过的时候返回的是一个 Object，校验通过的时候返回的是
   * 布尔值 true，所以这里写死判断为 true。
   */
  if (validateResult !== true) {
    return;
  }

  let resultData;

  if (props.mode === "view") {
    handleClose();
  }

  const postFormData = structuredClone(toRaw(pageData.formData));

  if (props.mode === "new") {
    // 新增
    resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  } else {
    // 更新
    // postFormData.updatedTime = new Date().toISOString();
    // postFormData.updatedBy = userStore.userData?.id;

    resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
